import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:talking/tools/config.dart';

import '../bean/bean.dart';
import '../tools/paint.dart';

class ForgetPassword extends StatefulWidget {
  @override
  ForgetPasswordPage createState() => ForgetPasswordPage();
}

class ForgetPasswordPage extends State<ForgetPassword>
    with TickerProviderStateMixin {
  List<BobbleBean> _bobbleList = [];
  Random _random = new Random(DateTime.now().microsecondsSinceEpoch);
  double _maxSpeed = 1.0;
  double _maxRadius = 100;
  double _maxTheta = 2 * pi;
  late AnimationController _animationController;
  bool autoForgetPassword = true;
  var emailController = TextEditingController();
  var yzmController = TextEditingController();
  var err = null;
  String yzm = "";
  var pass2Controller = TextEditingController();
  var passController = TextEditingController();

  var pass2Error;
  var passError;

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 20; i++) {
      BobbleBean bean = BobbleBean();
      bean.color = Color.fromARGB(_random.nextInt(200), 255, 255, 255);
      bean.offset = Offset(-1, -1);
      bean.speed = _random.nextDouble() * _maxSpeed;
      bean.radius = _random.nextDouble() * _maxRadius;
      bean.theta = _random.nextDouble() * _maxTheta;
      _bobbleList.add(bean);
    }
    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 5));
    _animationController.addListener(() {
      setState(() {});
    });
    _animationController.repeat();
    emailController.addListener(() {
      setState(() {
        err = null;
      });
    });
    pass2Controller.addListener(() {
      setState(() {
        pass2Error = null;
      });
    });
    passController.addListener(() {
      setState(() {
        passError = null;
      });
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    yzmController.dispose();
    emailController.dispose();

    passController.dispose();
    pass2Controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("登录"),
      ),
      body: Builder(
        builder: (BuildContext context) {
          return Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                      Colors.lightBlueAccent.withOpacity(0.3),
                      Colors.lightBlue.withOpacity(0.3),
                      Colors.blue.withOpacity(0.3),
                    ])),
              ),
              CustomPaint(
                size: MediaQuery.of(context).size,
                painter: MyPainter(list: _bobbleList, random: _random),
              ),
              Container(
                color: Colors.white.withOpacity(0.2),
              ),
              Container(
                width: double.infinity,
                height: double.infinity,
                alignment: Alignment.bottomCenter,
                child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Padding(
                          padding: EdgeInsets.only(bottom: 10),
                          child: TextField(
                            controller: emailController,
                            autofocus: true,
                            textInputAction: TextInputAction.next,
                            decoration: InputDecoration(
                                errorText: err,
                                suffixIcon: InkWell(
                                  child: Icon(Icons.send),
                                  onTap: () async {
                                    if (Constant.isEmail(
                                        emailController.text)) {
                                      yzm = Constant.generatePassword();
                                      Dio dio = Dio();
                                      await dio.get(
                                          "${Constant.BASE_URL}sendEmail/?email=${emailController.text}&yzm=${yzm}");
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(SnackBar(
                                              content: Text("已发送验证码"),
                                              duration: Duration(seconds: 5)));
                                    } else {
                                      setState(() {
                                        err = "邮箱格式有误";
                                      });
                                    }
                                  },
                                ),
                                labelText: "邮箱",
                                prefixIcon: const Icon(Icons.email),
                                border: OutlineInputBorder(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(10)),
                                    borderSide:
                                        BorderSide(color: Colors.blue))),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 10),
                          child: TextField(
                            controller: yzmController,
                            textInputAction: TextInputAction.go,
                            decoration: InputDecoration(
                              suffixIcon: InkWell(
                                child: Icon(Icons.close),
                                onTap: () {
                                  setState(() {
                                    yzmController.text = "";
                                  });
                                },
                              ),
                              prefixIcon:
                                  const Icon(Icons.verified_user_rounded),
                              labelText: "验证码",
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)),
                                  borderSide: BorderSide(color: Colors.blue)),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 10),
                          child: TextField(
                            controller: passController,
                            textInputAction: TextInputAction.go,
                            obscureText: true,
                            decoration: InputDecoration(
                                errorText: passError,
                                suffixIcon: InkWell(
                                  child: Icon(Icons.close),
                                  onTap: () {
                                    passController.clear();
                                  },
                                ),
                                labelText: "新密码",
                                prefixIcon: const Icon(Icons.lock),
                                border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)),
                                )),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 10),
                          child: TextField(
                            controller: pass2Controller,
                            textInputAction: TextInputAction.go,
                            obscureText: true,
                            decoration: InputDecoration(
                                errorText: pass2Error,
                                suffixIcon: InkWell(
                                  child: Icon(Icons.close),
                                  onTap: () {
                                    pass2Controller.clear();
                                  },
                                ),
                                labelText: "请再次输入",
                                prefixIcon: const Icon(Icons.replay),
                                border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)),
                                )),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 10),
                          child: ElevatedButton(
                            onPressed: () async {
                              if (yzmController.text != "" &&
                                  yzmController.text == yzm) {
                                if (passController.text == "") {
                                  setState(() {
                                    passError = "请输入密码";
                                  });
                                }
                                if (passController.text !=
                                    pass2Controller.text) {
                                  setState(() {
                                    pass2Error = "两次密码不一致";
                                  });
                                }
                                if (passError == null &&
                                    pass2Error == null &&
                                    emailController.text != "") {
                                  Dio dio = Dio();
                                  if ((await dio.get(
                                              "${Constant.BASE_URL}user/changePassword/?email=${emailController.text}&password=${passController.text}"))
                                          .data
                                          .toString() ==
                                      "修改成功") {
                                    SharedPreferences prefs =
                                        await SharedPreferences.getInstance();
                                    await prefs.setString(
                                        'email', emailController.text);
                                    await prefs.setString(
                                        'password', passController.text);
                                    prefs.setBool("autoLogin", true);

                                    Navigator.pop(context, "found");
                                  } else {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                        SnackBar(
                                            content: Text("修改失败"),
                                            duration: Duration(seconds: 5)));
                                  }
                                }
                              } else {
                                ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                        content: Text("验证码错误"),
                                        duration: Duration(seconds: 5)));
                              }
                            },
                            child: const Text("改密并登录"),
                            style: ButtonStyle(
                              minimumSize: MaterialStateProperty.all(
                                  Size(double.infinity, 40)),
                            ),
                          ),
                        ),
                      ],
                    )),
              )
            ],
          );
        },
      ),
    );
  }
}
